#pragma once
#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <string>
#include <pthread.h>
#include <cstring>
#include <functional>
#include <vector>
#include "Mutex.hpp"
using namespace MutexModel;
namespace ThreadModel
{
    int count = 1;
    using func_t = std::function<void()>;
    class Thread
    {
    private:
        // 因为在类中有this参数，所以在传参时将线程对象传入
        static void *threadFun(void *objs)
        {
            Thread *td = static_cast<Thread *>(objs);
            pthread_setname_np(td->_id, td->_name.c_str());
            if (td->IsDetach())
                td->Detach();

            td->_func();
            return nullptr;
        }
        bool IsDetach()
        {
            return _isdh;
        }

    public:
        Thread(func_t func) : _id(0), _isdh(false), _func(func)
        {
            Steward gj(_mutex);
            _name = "Thread-" + std::to_string(count);
            count++;
        }
        pthread_t& Gettid(){return _id;}
        // 创建线程
        bool start()
        {
            int n = pthread_create(&_id, nullptr, threadFun, this);
            if (n != 0)
            {
                std::cout << "创建失败" << std::endl;
                return false;
            }
            if (IsDetach())
            {
                Detach();
            }
            return true;
        }
        std::string &GetName()
        {
            return _name;
        }
        bool Detach()
        {
            int n = pthread_detach(_id);
            if (n != 0)
            {
                std::cout << "分离失败" << std::endl;
                return false;
            }
            std::cout << "分离成功" << std::endl;
            _isdh = true;
            return true;
        }
        bool Join()
        {
            if (IsDetach())
            {
                std::cout << "线程已经被分离，无需等待" << std::endl;
                return false;
            }
            int n = pthread_join(_id, &_retu);
            if (n != 0)
            {
                std::cout << "等待失败" << std::endl;
                return false;
            }
            //std::cout << "等待成功，返回值为：" << _retu << std::endl;
            return true;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _id;
        std::string _name;
        bool _isdh; // 默认不分离
        void *_retu;
        func_t _func;
        Mutex _mutex;
    };

}